const _ = require("lodash");

// ✅ 智能选号策略（基于频率 + 马尔科夫链 + 奇偶比）
function select32NumbersBySmartStrategy(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  // 1️⃣ 构建频率表
  const freqMap = _.countBy(temp.map((v) => v.number));

  // 2️⃣ 构建马尔科夫转移矩阵（前一个号 => 当前号）
  const transitionMap = {};
  for (let i = 1; i < temp.length; i++) {
    const prev = temp[i - 1].number;
    const curr = temp[i].number;
    if (!transitionMap[prev]) transitionMap[prev] = {};
    if (!transitionMap[prev][curr]) transitionMap[prev][curr] = 0;
    transitionMap[prev][curr]++;
  }

  // 3️⃣ 计算当前热门号
  const hotNumbers = Object.entries(freqMap)
    .sort((a, b) => b[1] - a[1])
    .map((x) => x[0])
    .slice(0, 20); // 取前 20 热门

  // 4️⃣ 计算奇偶比（奇偶平衡）
  const evenNumbers = [];
  const oddNumbers = [];
  for (let i = 1; i <= 49; i++) {
    const num = i.toString().padStart(2, "0");
    if (parseInt(num) % 2 === 0) {
      evenNumbers.push(num);
    } else {
      oddNumbers.push(num);
    }
  }

  // 5️⃣ 综合评分：频率得分 + 马尔科夫跳转得分 + 奇偶调和
  const scoreMap = {};
  for (const num of allNumbers) {
    const freqScore = freqMap[num] || 0;

    // 马尔科夫分数（以最近一期为基准）
    const lastNum = temp[temp.length - 1].number;
    const markovScore = (transitionMap[lastNum]?.[num] || 0) * 2;

    const parityScore = parseInt(num) % 2 === 0 ? 1 : 1; // 简化处理：奇偶都给1分

    scoreMap[num] = freqScore + markovScore + parityScore;
  }

  // 6️⃣ 最终选择得分前 32 的号码
  return Object.entries(scoreMap)
    .sort((a, b) => b[1] - a[1])
    .map((x) => x[0])
    .slice(0, 32);
}

module.exports = select32NumbersBySmartStrategy;
